from django.db import models
from django.dispatch import dispatcher
from django.conf import settings
import os, shutil

class RenamingImageField(models.ImageField):
    """It's like an image field but the filename is always the date."""
    def __init__(self, *args, **kwargs):
        super(RenamingImageField,self).__init__(*args, **kwargs)
    
    def _save(self, instance=None):
        """
        handles the renaming
        e.g. changes 'whatever/whatever/something.png'
        into 'whatever/whatever/2007-12-18.png'
        """
        if instance == None:
            return
        old_filename = instance.comic
        path = os.path.dirname(old_filename)
        
        old_base, ext = os.path.splitext(os.path.basename(old_filename))
        new_filename = os.path.join(path, str(instance.date) + ext)

        if new_filename != old_filename:
            try:
                shutil.move(os.path.join(settings.MEDIA_ROOT,old_filename),
                            os.path.join(settings.MEDIA_ROOT,new_filename))
            except IOError:
                new_filename = old_filename
        
        instance.comic = new_filename
    
    def contribute_to_class(self, cls, name):
        super(RenamingImageField,self).contribute_to_class(cls,name)
        dispatcher.connect(self._save, models.signals.pre_save, sender=cls)
